/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */
package com.ecarx.systemui.plugin.ui.dialog;
import static android.media.AudioAttributes.USAGE_MEDIA;
import static android.media.AudioManager.ADJUST_MUTE;
import static android.media.AudioManager.ADJUST_UNMUTE;
import static android.media.AudioSystem.STREAM_MUSIC;
import android.annotation.SuppressLint;
import android.car.media.CarAudioManager;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;
import com.ecarx.systemui.plugin.AppConstants;
import com.ecarx.systemui.plugin.PluginContext;
import com.ecarx.systemui.plugin.R;
import com.ecarx.systemui.plugin.common.CommonUtils;
import com.ecarx.systemui.plugin.controller.CarVoiceController;
import com.ecarx.systemui.plugin.ui.dialog.base.AutoCloseDialog;
import com.ecarx.systemui.plugin.ui.dialog.base.DialogManager;
import com.ecarx.systemui.plugin.utils.DensityUtils;
import com.ecarx.systemui.plugin.utils.LogUtils;
import com.ecarx.systemui.plugin.utils.ThreadUtils;

/**
 * @author : jiangjiao.ying
 * @date : 2022/08/17
 * @describe :
 */
public class GlobalVolumeDialog extends AutoCloseDialog implements View.OnClickListener {
    private static final String TAG = "GlobalVolumeDialogTag";
    final int DIALOG_DELAY_TIME = 150;
    private CarAudioManager mCarAudioManager;
    private CarVoiceController mCarVoiceController;
    private View rootView;
    private SeekBar seekBar;
    private ImageView ivMusic;
    private ImageView ivVolumeMute;
    private ImageView ivMore;
    final int MSG_SET_VOICE = 1000;
    private int mCurGroupId = 0;
    private int mCurrentUsage = 0;


    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            switch (what) {
                case MSG_SET_VOICE:
                    int volume = msg.arg1;
                    LogUtils.d(TAG, "设置全局音量:" + volume);
                    mCarAudioManager.setGroupVolume(mCurGroupId, volume, AudioManager.FLAG_PLAY_SOUND);
                    boolean isMute =mCarVoiceController.isStreamMuteAll();
                    checkVolumeIcon(isMute);
                    checkMusicIcon(isMute || volume == 0);
                    break;

            }
        }
    };

    public GlobalVolumeDialog(@NonNull Context context) {
        this(context, 0);
    }

    public GlobalVolumeDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i(TAG, "onCreate");
        setCancelable(true);
        setCanceledOnTouchOutside(true);
        initConfig();
        setContentView(R.layout.dialog_global_volume);
        mCarVoiceController = CarVoiceController.getCarVoiceController();
        mCarAudioManager = mCarVoiceController.getCarAudioManager();
        initCarVolume();
        initView();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        LogUtils.i(TAG, "onWindowFocusChanged");
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        LogUtils.i(TAG, "onAttachedToWindow");
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        LogUtils.i(TAG, "onDetachedFromWindow");
    }

    private void initCarVolume() {
        mCurrentUsage = mCarAudioManager.getCurrentActiveUsage(0);
        if (mCurrentUsage == 0) { //如果没有获取到当前音源，默认显示多媒体音源
            mCurrentUsage = USAGE_MEDIA;
        }
        mCurGroupId = mCarAudioManager.getVolumeGroupIdForUsage(mCurrentUsage);
        LogUtils.i(TAG, "mCurrentUsage" + mCurrentUsage + ", mCurGroupId =" + mCurGroupId);
    }

    private void initView() {
        rootView = findViewById(R.id.root_view);
        rootView.setOnClickListener(v -> startTimingClose());
        ivMusic = findViewById(R.id.iv_music);
        seekBar = findViewById(R.id.seek_bar);
        seekBar.setMax(mCarVoiceController.getGlobalMaxVolume(mCurGroupId));
        seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
        ivMore = findViewById(R.id.iv_more);
        ivMore.setOnClickListener(this);
        ivVolumeMute = findViewById(R.id.iv_mute);
        ivVolumeMute.setOnClickListener(this);
        showInitView();
    }


    private void showInitView() {
        if (mCarAudioManager == null) {
            return;
        }
        int volume = mCarAudioManager.getGroupVolume(mCurGroupId);
        boolean isMute = mCarVoiceController.isStreamMuteAll();
        seekBar.setProgress(isMute ? 0 : volume);
        checkVolumeIcon(isMute);
        checkMusicIcon(isMute || volume == 0);
    }


    @SuppressLint("ClickableViewAccessibility")
    private void initConfig() {
        Window window = getWindow();
        if (window != null) {
            int type = DialogManager.TYPE_VOLUME_OVERLAY;
            window.requestFeature(Window.FEATURE_NO_TITLE);
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND
                    | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
            window.setType(type);
            window.setWindowAnimations(com.android.internal.R.style.Animation_Toast);

            final WindowManager.LayoutParams lp = window.getAttributes();
            lp.format = PixelFormat.TRANSLUCENT;
            lp.gravity = Gravity.START | Gravity.TOP;
            lp.windowAnimations = -1;
            lp.x = 1570;
            lp.y = 1080;
            window.setAttributes(lp);
        }
    }

    private final SeekBar.OnSeekBarChangeListener onSeekBarChangeListener =
            new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    LogUtils.d(TAG, "onProgressChanged progress:" + progress
                            + ", fromUser:" + fromUser );
                    if (fromUser && mCarAudioManager != null && mCarVoiceController != null) {
                        updateProgress(progress);
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    LogUtils.d(TAG, "onStartTrackingTouch start Touch");
                    cancelTimingClose();
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    LogUtils.d(TAG, "onStopTrackingTouch stop up");
                    startTimingClose();
                }
            };

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        if (CommonUtils.isFastClick()) {
            LogUtils.d(TAG, "静音连点 未超过250毫秒");
            return;
        }
        switch (view.getId()) {
            case R.id.iv_mute:
                LogUtils.i(TAG, "iv_mute clicked");
                boolean isAllMute = mCarVoiceController.isStreamMuteAll();
                if (!isAllMute) {
                    //点击静音，设置静音图标，进度条为0
                    seekBar.setProgress(0);
                    checkVolumeIcon(true);
                    checkMusicIcon(true);
                } else {
                    //恢复静音之前的音量
                    mCarAudioManager.setGroupVolume(mCurGroupId, 0, ADJUST_UNMUTE);
                    LogUtils.i(TAG, "mCurGroupId = " + mCurGroupId + ", mCurrentUsage = " + mCurrentUsage);
                    int volume = mCarAudioManager.getGroupVolume(mCurGroupId);
                    seekBar.setProgress(volume);
                    checkVolumeIcon(false);
                    checkMusicIcon(false);
                    //同步VolumeDialog显示
                    //mCarVoiceController.setCurrentStreamUnMute(mAudioManager, mCurrentUsage);
                }
                mCarVoiceController.setStreamMuteAll(!isAllMute);
                break;
            case R.id.iv_more:
                LogUtils.i(TAG, "iv_more clicked");
                cancelTimingClose();
                dismiss();
                DialogManager.getDialogManager().showVolumeDialog(PluginContext.getInstance().getPluginContext(), true);
                break;

        }

    }

    private void checkVolumeIcon(boolean isMute) {
        LogUtils.d(TAG, "checkVolumeIcon isMute All =" + isMute);
        ivVolumeMute.setImageDrawable(AppCompatResources.getDrawable(
                getContext(),isMute ? R.drawable.ic_dialog_global_voice_mute : R.drawable.ic_dialog_global_voice_normal));
    }

    private void checkMusicIcon(boolean isChecked) {
        LogUtils.d(TAG, "checkMusicIcon isChecked All =" + isChecked);
        ivMusic.setImageDrawable(AppCompatResources.getDrawable(
                getContext(),isChecked ? R.drawable.dialog_top_media_mute : R.drawable.dialog_top_media));
    }

    private void updateProgress(int progress) {
        handler.removeMessages(MSG_SET_VOICE);
        Message obtain = Message.obtain();
        obtain.what = MSG_SET_VOICE;
        obtain.arg1 = progress;
        handler.sendMessageDelayed(obtain, 50);
    }


    @Override
    public void dismiss() {
        GlobalVolumeDialog.super.dismiss();
        DialogManager.getDialogManager().cleanGlobalVolumeDialog();
    }


    @Override
    protected boolean isAutoDismiss() {
        return false;
    }

}
